/*
 * @Description:
 * @Version: 1.0
 * @Autor: gaoluo
 * @Date: 2021-08-20 14:43:01
 * @LastEditors: gaoluo
 * @LastEditTime: 2021-12-04 11:46:50
 * @FilePath: /nhw/src/api/index.js
 */
import axios from 'axios';
import { Toast } from 'vant';
import { getTokenByUakey, setToken } from "@/utils/token.js";

const baseURL = process.env.NODE_ENV === 'production' ? process.env.VUE_APP_SERVERBASE + '/nhw/api/' : '/nhw/api/'

const request = axios.create({
  baseURL: '/nhw/api',
  timeout: 1000 * 10,
})

request.interceptors.response.use(config => {
  const { data } = config;
  if (data.state == 0) {
    return data
  } else {
    Toast.fail(data.msgInfo)
    throw (data.msgInfo);
  }
}, error => {
  Toast.fail('网络异常')
  return Promise.reject(error);
})


// 请求拦截器
request.interceptors.request.use(async (config) => {

  const uakey = window.localStorage.getItem('uakey');
  const token = getTokenByUakey(uakey); //获取

  const res = await token; //过期或者没有 请求返回

  if (typeof res === 'string') { //有token直接返回
    config.url = config.url + '?access_token=' + res;
    return config;
  } else {
    const { data } = res;
    if (data.code == 200) { //获取成功
      setToken({
        access_token: data.access_token,
        expires_in: data.expires_in,
        token_time: Date.now()
      }, uakey);
      config.url = config.url + '?access_token=' + data.access_token;
      return config;
    }
    else { //获取失败 跳转登录
      Toast('登录过期,请重新登录！')
    }
  }

  //测试用
  // return config;
})

export default request;